Vue.component('ht-editor', {
    name:'ht-editor',
    template: `
        <div class="ht-editor">
            <textarea :id="randomId">{{ value }}</textarea>
        </div>
    `,
    props: {
        value: {
            type: String,
            default: "",
        },
        height: {
            type: Number,
            default: 350,
        },
    },
    data() {
        return {
            editorHeight: this.height,
            randomId: 'editor_' + (Math.random() * 100000000000000000),
            instance: null,
            // scriptTagStatus -> 0:代码未加载，1:两个代码依赖加载了一个，2:两个代码依赖都已经加载完成
            scriptTagStatus: 0
        }
    },
    created() {
        window.UEDITOR_HOME_URL = '/static/ueditor/'
        if (window.UE !== undefined) {
            // 如果全局对象存在，说明编辑器代码已经初始化完成，直接加载编辑器
            this.scriptTagStatus = 2;
            this.initEditor();
        } else {
            // 如果全局对象不存在，说明编辑器代码还没有加载完成，需要加载编辑器代码
            // this.insertScriptTag();
        }
        console.log(this)
    },
    methods: {
        initEditor() {
            var that = this
            // scriptTagStatus 为 2 的时候，说明两个必需引入的 js 文件都已经被引入，且加载完成
            if (this.instance === null) {
                // if (this.scriptTagStatus === 2 && this.instance === null) {
                    // Vue 异步执行 DOM 更新，这样一来代码执行到这里的时候可能 template 里面的 script 标签还没真正创建
                // 所以，我们只能在 nextTick 里面初始化 UEditor
                this.$nextTick(() => {
                    window.htEditor = that.instance = window.UE.getEditor(that.randomId, {
                        zIndex: 1000,
                        initialFrameHeight: that.editorHeight,
                        initialFrameWidth: "99%",
                        lang: 'zh-cn'
                    });
                    // 绑定事件，当 UEditor 初始化完成后，将编辑器实例通过自定义的 ready 事件交出去
                    that.instance.addListener('ready', () => {
                        that.instance.setContent(that.value)
                    });
                    that.instance.addListener('contentChange', () => {
                        that.$emit('input',that.instance.getContent())
                        // console.log(that.instance.getContent())
                    });
                });
            } else {
                console.log(that.instance)
            }
        },
        getUeContent() {
            return this.instance.getContent()
        },
        setUeContent(content) {
            console.log('value_content', content)
            if (this.instance) {
                console.log('set', content)
                this.instance.setContent(content)
            }
        },
    },

    watch: {
        value(v) {
            if (this.instance.getContent() !== v) {
                this.instance.setContent(v)
                console.log(v)
            }
        }
    }
})

Vue.component('ht-tag', {
    template: `
      <span :style="{backgroundColor:backcolor}" class="ht-tag">{{title}}</span>
    `,
    props: {
        color: {
            type: String,
            default: "#409EFF",
        },
        value: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            title: this.value,
            backcolor: this.color
        }
    },
})
Vue.component('ht-upload', {
    template: `
        <el-upload action="/admin/Uploadify/upload"
                    class="upload-demo"
                   :on-success="uploadSuccess"
                   :show-file-list="false"
                   :multiple="false">
            <el-button :size="size" :type="type" icon="el-icon-plus">上传</el-button>
        </el-upload>
    `,
    props: {
        type:{
            type: String,
            default: "success",
        },
        size: {
            type: String,
            default: "mini",
        },
        value: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            title: this.value,
        }
    },
    created() {

    },
    methods: {
        uploadSuccess(response,file,fileList) {
            let that = this
            console.log(response,file,fileList)
            if (response.code === 1) {
                this.$emit('input',response.url)
            } else {
                this.showErrorMsg(that,response.msg)
            }
        },
    },
})
Vue.component('ht-table-image', {
    template: `
        <el-image
            class="ht-table-image"
            fit="scale-down"
            :src="checkExt" @click="showImage"
        ></el-image>
    `,
    props: {
        value: {
            type: Object,
            default: {},
        },
    },
    data() {
        return {
            row:this.value,
            checkExt:'/static/img/mp4.png'
        }
    },
    created() {
        this.checkExt1()
    },
    methods: {
        checkExt1() {
            let row = this.row
            if (!row) {
                return
            }

            if (['.mp3','.mp4'].indexOf(row.ext) !== -1) {
                this.checkExt =  "/static/img/video.png"
            }
            if (['.jpg', '.bmp', '.gif', '.png','.webp','.jpeg'].indexOf(row.ext) !== -1) {
                this.checkExt =  row.path
            }
            if (['.zip','.rar','.gz'].indexOf(row.ext) !== -1) {
                this.checkExt =  "/static/img/zip.png"
            }
            if (['.doc','.docx'].indexOf(row.ext) !== -1) {
                this.checkExt =  "/static/img/word.png"
            }
            if (['.pdf'].indexOf(row.ext) !== -1) {
                this.checkExt =  "/static/img/pdf.png"
            }
            if (['.xls','.xlsx'].indexOf(row.ext) !== -1) {
                this.checkExt =  "/static/img/xlsx.png"
            }
            if (['.ppt','.pptx'].indexOf(row.ext) !== -1) {
                this.checkExt =  "/static/img/pptx.png"
            }
        },
        showImage() {
            let row = this.row
            if (['.jpg', '.bmp', '.gif', '.png','.webp','.jpeg'].indexOf(row.ext) !== -1) {
                top.showImg(row.path)
            }
            if (['.mp3','.mp4'].indexOf(row.ext) !== -1) {
                top.showImg('<video controls src="'+row.path+'">',"html")
            }
            if (['.pdf'].indexOf(row.ext) !== -1) {
                top.showImg(row.path,"pdf")
            }
        },
    },

    watch: {
        value(v){
            this.row = v
            this.checkExt1()
        }
    }
})
Vue.component('ht-image-manage', {
    name:'ht-image-manage',
    template: `
        <el-dialog title="附件管理" :visible.sync="dialogTableVisible" 
            :destroy-on-close="true" width="90%" height="90%" top="20px" @close="close"
            :append-to-body="true" z-index="9999999">
            <div class="ht-tool">
                <div class="ht-tool-left">
                    <el-upload
                        class="upload-demo"
                        action="/admin/Uploadify/upload"
                       :on-success="uploadSuccess"
                       :show-file-list="false"
                       :multiple="true">
                      <el-button size="mini" ref="upload" type="success" icon="el-icon-upload2">上传</el-button>
                    </el-upload>
                      <el-button size="mini" @click="submit" :disabled="!select_list.length" type="primary" icon="el-icon-check">选择</el-button>
                      <span style="color: #E6A23C;margin-left: 5px" >已经选择 {{select_list.length}}/{{count}} 个</span>
                </div>
            </div>
            <div class="ht-main-body">
                    <el-table :data="tableData" border :row-key="getRowKey" ref="table"
                        @select-all="selectAll" @row-click="rowClick"
                        @select="select" header-row-class-name="ht-table-header">
                        <el-table-column
                              :reserve-selection="true" 
                              type="selection"
                              width="55">
                        </el-table-column>
                        <el-table-column
                                prop="name"
                                label="类型" width="100px">
                            <template slot-scope="scope">
                                <ht-table-image :value="scope.row"></ht-table-image>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="name"
                                label="名称"
                                width="280px">
                        </el-table-column>
                        <el-table-column
                                prop="id"
                                label="大小"
                                width="100px" :formatter="formatSize">
                        </el-table-column>
                        <el-table-column
                                align="center"
                                prop="path"
                                label="路径">
                        </el-table-column>
                    </el-table>
                    <div class="ht-main-page">
                        <el-pagination
                                @size-change="manageSizeChange"
                                @current-change="manageCurrentChange"
                                :current-page="managePage"
                                :page-sizes="[3,10, 200, 300, 400]"
                                :page-size="manageLimit"   
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="manageTotal">
                        </el-pagination>
                    </div>
            </div>
        </el-dialog>
    `,
    props: {
        isshow:{
            type:Boolean,
            default:false
        },
        type:{
            type:String,
            default:'image',
        },
        category:{
            type:String,
            default:''
        },
        value:{
            type:String,
            default:''
        },
        count:{
            type:Number,
            default:1
        }
    },
    data() {
        return {
            dialogTableVisible:this.isshow,
            manageTotal:1,
            managePage:1,
            manageLimit:10,
            title:'',
            tableData:[],
            currentRow: null,
            select_list:[],
        }
    },
    created() {
        console.log("imageManageCreate")
        this.getManageData()
    },
    methods: {
        uploadSuccess(response,file,fileList) {
            let that = this
            console.log(response,file,fileList)
            if (response.code === 1) {
                this.getManageData()
            } else {
                this.showErrorMsg(response.msg)
            }
        },
        submit(){
            let path = []
            if (this.select_list.length) {
                this.select_list.forEach((item)=>{
                    path.push(item.path)
                })
            }
            this.dialogTableVisible = false
            this.$emit('submit',path,this.value)
        },
        selectAll(v) {
            if (v.length > this.count) {
                this.showErrorMsg('只能选择' + this.count + "张")
                this.$refs.table.clearSelection()
                this.select_list.map((item)=>{
                    this.$refs.table.toggleRowSelection(item,true)
                })
            } else {
                this.select_list = JSON.parse(JSON.stringify(v));
            }
            console.log('selectAll',this.select_list)
        },
        select(v,row) {
            this.select_list = v
            console.log("v",v)
            console.log("row",row)
            if (this.select_list.length > this.count) {
                this.select_list.splice(0,1)
            }
            if (this.select_list.length) {
                this.$refs.table.clearSelection()
                this.select_list.map((item)=>{
                    this.$refs.table.toggleRowSelection(item,true)
                })
            }
            console.log('select_list',this.select_list)
        },
        rowClick(row) {
            this.$refs.table.toggleRowSelection(row)
            this.select_list  = this.$refs.table.selection
            if (this.select_list.length > this.count) {
                this.select_list.splice(0,1)
                this.$refs.table.clearSelection()
                this.select_list.map((item)=>{
                    this.$refs.table.toggleRowSelection(item,true)
                })
            }
        },
        formatSize(row) {
            var fileSizeByte = row.size;
            var fileSizeMsg = "";
            if (fileSizeByte < 1048576) fileSizeMsg = (fileSizeByte / 1024).toFixed(2) + "KB";
            else if (fileSizeByte == 1048576) fileSizeMsg = "1MB";
            else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824) fileSizeMsg = (fileSizeByte / (1024 * 1024)).toFixed(2) + "MB";
            else if (fileSizeByte > 1048576 && fileSizeByte == 1073741824) fileSizeMsg = "1GB";
            else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776) fileSizeMsg = (fileSizeByte / (1024 * 1024 * 1024)).toFixed(2) + "GB";
            else fileSizeMsg = "文件超过1TB";
            return fileSizeMsg;
        },
        getRowKey(row) {
            return row.id
        },
        getManageData:function() {
            var that = this
            axios.post('/admin/uploadify/attachment',{
                limit:that.manageLimit,
                page:that.managePage,
                type:that.type,
                title:that.title
            }).then((res)=>{
                console.log(res.data)
                that.tableData = res.data.data.data
                that.manageTotal = res.data.data.total
            })
        },
        close(){
            this.dialogTableVisible = false
            this.select_list = []
            this.$emit('close')
        },
        manageSizeChange:function(e) {
            this.manageLimit = e
        },
        manageCurrentChange:function(e) {
            this.managePage = e
        }
    },
    watch: {
        isshow(v) {
            this.dialogTableVisible = v
            console.log('child',v)
        },
        managePage(v) {
            this.getManageData()
        },
        manageLimit() {
            this.getManageData()
        }
    }
})
Vue.component('ht-chunk-upload', {
    name:'ht-chunk-upload',
    template: `
        <el-dialog title="上传" :visible.sync="dialogTableVisible" 
            :destroy-on-close="true" width="90%" top="20px" @close="close"
            :append-to-body="true" z-index="9999999">
            <el-form label-width="80px">
                <el-form-item label="选择文件">
                <input type="file" ref="myfile" @input="fileChange($event)" placeholder="请选择文件" style="width: 70%">
<!--                    <el-input placeholder="请选择文件" style="width: 70%"></el-input> -->
                </el-form-item>
                <el-form-item label="上传进度">
                    <el-progress :text-inside="true" status="success" :stroke-width="20" :percentage="percent"></el-progress>
                </el-form-item>
                <el-form-item label="">
                    <el-button type="primary" @click="start">开始上传</el-button>
                    <el-button type="" @click="close">返回</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    `,
    props: {
        show:{
            type:Boolean,
            default:false
        },
        type:{
            type:String,
            default:'',
        },
        value:{
            type:String,
            default:'',
        },
        category:{
            type:String,
            default:''
        }
    },
    data() {
        return {
            dialogTableVisible:this.show,
            manageTotal:1,
            managePage:1,
            manageLimit:10,
            title:'',
            tableData:[],
            currentRow: null,
            file:{
                "name":""
            },
            is_upload:false,
            uploader:null,
            fileMd5:'',
            ext:'',
            percent:0,
            path:''
        }
    },
    mounted(){
        var that = this;
        console.log(WebUploader)
        WebUploader.Uploader.register({
            "before-send-file":"beforeSendFile",//整个文件上传前
            "before-send":"beforeSend",  //每个分片上传前
            "after-send-file":"afterSendFile",  //分片上传完毕
        },{
            beforeSend: function (block) {
                if (that.is_upload) {
                    var deferred = WebUploader.Deferred();
                    $.ajax({
                        type: "GET",
                        url: "/admin/chunk/checkChunk",
                        data: {
                            //文件唯一标记
                            md5: that.fileMd5,
                            //当前分块下标
                            chunk: block.chunk,
                            //当前分块大小
                            chunkSize: block.end - block.start
                        },
                        dataType: "json",
                        success: function (res) {
                            if (res.code == 1) {
                                //分块存在，跳过
                                console.log(block.chunk + "reject");
                                deferred.reject();
                            } else {
                                //分块不存在或不完整，重新发送该分块内容
                                console.log(block.chunk + "resolve");
                                deferred.resolve();
                            }
                        }
                    });
                    return deferred.promise();
                }
            }
        });
        that.uploader = WebUploader.create({

            // swf文件路径
            swf: '/static/webuploader/Uploader.swf',

            // 文件接收服务端。
            server: '/admin/chunk/chunkUpload',
            extensions: 'jpg,png,bmp,gif,rar,zip,gz,mp4,avi,mp3,mov,flv,mpeg,doc,docx,pdf',
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            // pick: {
            //     id: "#upload",
            // },
            formData: {
            },
            chunked: true, //是否要分片处理大文件上传
            chunkSize: 5*1024*1024, //分片上传，每片2M，默认是5M
            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            resize: false
        });
        that.uploadInit()
    },
    created() {
        var that = this;
    },
    methods: {
        fileChange(e) {
            this.uploader.reset();
            console.log(e.target.files[0])
            this.uploader.addFiles(e.target.files[0])
        },
        start(){
            this.uploader.upload()
        },
        uploadInit(){
            var load ;
            var that = this ;
            console.log("init",this.uploader);
            that.uploader.on('fileQueued', function( file ) {
                that.percent = 0;
                that.path = '';
                load = layer.load(1,{
                    shade: [0.1,'#000']
                });
                that.uploader.md5File(file,0,10*1024*1024)
                    .progress(function (percentage) {
                        $("#path").val("获取文件信息中……"+(percentage * 100).toFixed(2) + '%');
                    })
                    .then(function (val) {
                        $("#path").val(file.name + " 等待上传");
                        layer.closeAll();
                        var formData = that.uploader.option("formData");
                        formData.md5 = val;
                        formData.ext = file.ext;
                        that.uploader.option("formData",formData);
                        that.fileMd5 = val;
                        that.ext = file.ext;
                        $.post('/admin/chunk/checkMd5',{md5:val}, function (res) {
                            if (res.code == 1) { // 已经上传过
                                that.is_upload = "true"
                            }  else {
                                that.is_upload = "false"
                            }
                        })
                    })
            });
            that.uploader.on('uploadProgress', function( file, percentage ) {
                that.percent = parseInt(percentage * 100);
            });
            that.uploader.on('uploadSuccess', function (file,res) {
                console.log(file,res)
                layer.msg("处理中",{shade: [0.1,'#000'],icon:16,time:9999999});
                $.post("/admin/chunk/mergeChunk",{md5:that.fileMd5,ext:that.ext,type:file.type,name:file.name,size:file.size}, function (res1) {
                    layer.closeAll();
                    if (res1.code == 1) {
                        layer.msg("上传成功",{time:500},function (){
                            that.path = res1.data.path;
                            console.log("res",res1.data.path)
                            that.close()
                        });
                    } else  {
                        layer.alert("上传失败")
                    }
                })
            });
            that.uploader.on('uploadAccept',function (file,res) {
                if (res.code == 0) {
                    layer.alert(res.msg)
                    return false;
                }
            });
        },
        close(){
            console.log("temp",this.path);
            this.$emit('close',this.path)
            this.dialogTableVisible = false
        },
    },
    watch: {
        show(v) {
            this.dialogTableVisible = v
        },
    }
})

